<?php

/**
 * @Author: wuchenge
 * @Date: 2020-11-30 16:03:41
 * @email: ligui0506@sina.com
 * @descript: 后台登录相关控制器
 */

namespace App\Admin\v1;

use App\Http\Controllers\ApiController;
use App\Libraries\Token as JwtToken;
use App\Models\Admin;
use App\Models\Token;
use App\Requests\LoginRequest;
use App\Services\Permission;
use Carbon\Carbon;
use Illuminate\Http\Request;

class LoginController extends ApiController
{
    /**
     * 图形验证码
     * @return [type] [description]
     */
    public function captcha()
    {
        return $this->response(app('captcha')->create('default', true));
    }

    /**
     * 登录
     * @param  LoginRequest $request [description]
     * @return [type]                [description]
     */
    public function index(LoginRequest $request)
    {
        // 登录标识
        $account = $request->input('username');
        // 密码
        $pwd = $request->input('password');
        // 登录方式
        $type = $request->input('type');

        // 验证图片码
        if (!captcha_api_check($request->captcha, $request->key)) {
            return $this->setErrorCode(100105, '验证码错误')->response();
        }

        $admin = Admin::with('tokens')
            ->where('account', $account)
            ->first();

        if (!$admin) {
            return $this->setErrorCode(100104, '没有找到此用户')->response();
        }

        if ($admin->pwd != Admin::encodePwd($pwd)) {
            return $this->setErrorCode(100104, '密码错误')->response();
        }

        if ($admin->status == Admin::STATUS_NO) {
            return $this->setErrorCode(100103, '用户被禁用')->response();
        }

        // 版本加1
        $res = Token::updateVersion($admin->id, Admin::class, $type);

        if (!$res) {
            return $this->setErrorCode(100102, '登录失败，请连系管理员')->response();
        }

        // 更新最后登录时间, 和登录方式
        $admin->fill([
            'type'       => $type,
            'updated_at' => date('Y-m-d H:i:s'),
        ])->save();

        // 判断是否超级管理员
        // $user->is_supper = Permission::isSupper($user->id);

        $payload = [
            'id'        => $admin->id,
            'nick_name' => $admin->nick_name,
            'type'      => $type,
            'version'   => $res,
        ];

        // 获取当前用户的权限
        $permissions = Permission::getNodeBy($admin->id);

        $data = [
            'token'       => JwtToken::createToken($payload),
            'admin'       => $admin->toArray(),
            'permissions' => $permissions,
        ];

        \Log::debug($data);

        return $this->response($data);
    }
}
